#!/bin/bash
# Mini batch test - Quick validation with fork-join test scenarios
# Tests 5 different fork-join scenarios for quick performance validation

# Function to get active devices from "== Devices ==" section
get_all_targets() {
    # List iOS devices and Mac
    local in_active_section=false
    xcrun xctrace list devices 2>/dev/null | while IFS= read -r line; do
        if [[ "$line" == "== Devices ==" ]]; then
            in_active_section=true
            continue
        elif [[ "$line" == "== Devices Offline ==" ]] || [[ "$line" == "== Simulators ==" ]]; then
            break
        fi
        if [ "$in_active_section" = true ] && [[ -n "$line" && ! "$line" =~ ^[[:space:]]*$ ]]; then
            echo "$line"
        fi
    done
}

# Function to select device interactively
select_device() {
    echo "=== Available Targets ===" >&2
    local -a targets
    local count=0
    while IFS= read -r target; do
        targets+=("$target")
        count=$((count + 1))
        echo "[$count] $target" >&2
    done < <(get_all_targets)

    if [ $count -eq 0 ]; then
        echo "No targets found!" >&2
        exit 1
    fi

    echo "" >&2
    read -p "Please select a target (1-$count): " selection

    # Validate selection
    if ! [[ "$selection" =~ ^[0-9]+$ ]] || [ "$selection" -lt 1 ] || [ "$selection" -gt $count ]; then
        echo "Invalid selection!" >&2
        exit 1
    fi

    echo "${targets[$((selection-1))]}"
}
run_ios_test() {
    local test_case=$1
    local run_name=$2
    local extra_args=$3

    if [ "$FIRST_RUN" = true ]; then
        xcrun xctrace record \
            --instrument 'System Call Trace' \
            --instrument 'Thread State Trace' \
            --instrument 'os_signpost' \
            --device "$DEVICE" \
            --output "$OUTPUT_FILE" \
            --run-name "$run_name" \
            --time-limit 10s \
            --no-prompt \
            --launch "$BUNDLE_ID" -- --auto-test "$test_case" $extra_args
    else
        xcrun xctrace record \
            --append-run \
            --device "$DEVICE" \
            --output "$OUTPUT_FILE" \
            --run-name "$run_name" \
            --time-limit 10s \
            --no-prompt \
            --launch "$BUNDLE_ID" -- --auto-test "$test_case" $extra_args
    fi
}

run_mac_test() {
    local test_case=$1
    local run_name=$2
    local extra_args=$3

    if [ "$FIRST_RUN" = true ]; then
        echo "Starting trace collection for CLI..."
        xcrun xctrace record \
            --instrument 'System Call Trace' \
            --instrument 'Thread State Trace' \
            --instrument 'os_signpost' \
            --output "$OUTPUT_FILE" \
            --run-name "$run_name" \
            --time-limit 10s \
            --no-prompt \
            --launch -- "$CLI_BIN" --auto-test "$test_case" $extra_args
    else
        xcrun xctrace record \
            --append-run \
            --output "$OUTPUT_FILE" \
            --run-name "$run_name" \
            --time-limit 10s \
            --no-prompt \
            --launch -- "$CLI_BIN" --auto-test "$test_case" $extra_args
    fi
}

run_single_test() {
    local test_case=$1
    local run_name=$2
    local extra_args=$3

    echo "Running: $run_name"

    if [ "$TARGET_TYPE" = "ios" ]; then
        run_ios_test "$test_case" "$run_name" "$extra_args"
    else
        run_mac_test "$test_case" "$run_name" "$extra_args"
    fi

    if [ "$FIRST_RUN" = true ]; then
        FIRST_RUN=false
    fi
    echo ""
}
# Configuration
OUTPUT_DIR="${1:-~/Desktop}"
DEVICE_INPUT="${2}"
# Expand and convert to absolute path
OUTPUT_DIR=$(eval echo "$OUTPUT_DIR")
OUTPUT_DIR=$(cd "$OUTPUT_DIR" 2>/dev/null && pwd || echo "$OUTPUT_DIR")

# If device is not provided as argument, prompt user to select
if [ -z "$DEVICE_INPUT" ]; then
    TARGET_FULL=$(select_device)
    # Extract simple device name (matching full script exactly)
    DEVICE=$(echo "$TARGET_FULL" | sed 's/ *(.*//')
    # Extract UUID for installation
    DEVICE_UUID=$(echo "$TARGET_FULL" | sed 's/.*(\([^)]*\))$/\1/')
    # Check if Mac to set target type
    if [[ "$TARGET_FULL" == *"Mac"* ]]; then
        TARGET_TYPE="mac"
    else
        TARGET_TYPE="ios"
    fi
else
    # If input contains "mac" treat as Mac, otherwise as iOS device
    if [[ "$DEVICE_INPUT" =~ -i ]] || [[ "$DEVICE_INPUT" =~ "Mac" ]]; then
        TARGET_TYPE="mac"
        DEVICE="My Mac"
        TARGET_FULL="Mac"
    else
        TARGET_TYPE="ios"
        # For iOS, extract simple device name (remove version and UUID)
        DEVICE=$(echo "$DEVICE_INPUT" | sed 's/ ([^)]*)$//')
        TARGET_FULL="$DEVICE_INPUT"
        DEVICE_UUID="$DEVICE_INPUT"
    fi
fi

echo ""
echo "=== Mini Batch Test (Fork-Join Samples) ==="
echo "Target: $TARGET_FULL"
echo "Type: $TARGET_TYPE (CLI + Trace)"
echo "Output: $OUTPUT_DIR"
echo ""

# Project configuration
PROJECT_DIR="$HOME/Documents/XcodeWorkspace/GCDBenchmark"
PROJECT_FILE="$PROJECT_DIR/GCDBenchmark.xcodeproj"
SCHEME="GCDBenchmark"

# CLI binary path
CLI_BIN="$HOME/Library/Developer/Xcode/DerivedData/Build/Products/Debug/GCDBenchmarkCLI"

if [ "$TARGET_TYPE" = "ios" ]; then
    echo "=== Building and Installing App ==="
    echo "Project: $PROJECT_FILE"
    echo "Scheme: $SCHEME"
    echo "Device: $DEVICE ($DEVICE_UUID)"
    echo ""

    # Build for device
    echo "Building app for device..."
    xcodebuild\
        -project "$PROJECT_FILE"\
        -scheme "$SCHEME"\
        -configuration Release\
        build-for-testing\
        -destination "generic/platform=iOS"\
        -derivedDataPath "$HOME/Library/Developer/Xcode/DerivedData" 2>&1 | tail -10
    # Find the built .app
    APP_BUNDLE=$(find "$HOME/Library/Developer/Xcode/DerivedData" -name "GCDBenchmark.app" -type d -path "*Release-iphoneos*" 2>/dev/null | tail -1)
    if [ -z "$APP_BUNDLE" ]; then
        echo "Error: Could not find built app"
        exit 1
    fi
    echo "Found app at: $APP_BUNDLE"
    echo ""

    echo "Installing app to device..."
    # Install app to device using devicectl
    xcrun devicectl device install app\
        --device "$DEVICE_UUID"\
        "$APP_BUNDLE" 2>&1 | grep -E "(installed|bundleID|error)" | head -5
    echo ""
    echo "=== Build and Installation Complete ==="
    echo ""

    # Bundle identifier
    BUNDLE_ID="com.ufogxl.GCDBenchmark"
else
    echo "=== Building CLI on Mac ==="
    echo "Building GCDBenchmarkCLI..."
    xcodebuild\
        -project "$PROJECT_FILE"\
        -scheme "GCDBenchmarkCLI"\
        -configuration Debug\
        build\
        -derivedDataPath "$HOME/Library/Developer/Xcode/DerivedData" 2>&1 | tail -10
    echo ""

    # Copy playback files to DerivedData directory (TCC doesn't restrict this location)
    echo "Copying playback files to DerivedData..."
    PLAYBACK_SRC_DIR="$PROJECT_DIR/PlaybackCases"
    PLAYBACK_DEST_DIR="$HOME/Library/Developer/Xcode/DerivedData/Build/Products/PlaybackCases"
    if [ -d "$PLAYBACK_SRC_DIR" ]; then
        mkdir -p "$PLAYBACK_DEST_DIR"
        cp "$PLAYBACK_SRC_DIR"/*.playback "$PLAYBACK_DEST_DIR/" 2>/dev/null || true
        echo "Playback files copied to: $PLAYBACK_DEST_DIR"
        ls -la "$PLAYBACK_DEST_DIR"
    fi
    echo ""

    # For Mac mode, we don't use bundle ID
    BUNDLE_ID="CLI-Binary"
fi

echo "Bundle ID/Target: $BUNDLE_ID"
echo ""

# Create result folder
RESULT_FOLDER="$OUTPUT_DIR/GCDBenchmark_result_$(date +%Y%m%d_%H%M%S)"
mkdir -p "$RESULT_FOLDER"
echo "Created result folder: $RESULT_FOLDER"
echo ""

# Set output file to save in result folder
OUTPUT_FILE="$RESULT_FOLDER/GCDBenchmark_mini.trace"
echo "Output: $OUTPUT_FILE"
echo ""

echo "=== Starting Mini Batch Test Recording ==="
echo "Testing 2 scenarios..."
echo ""

FIRST_RUN=true

## Test 1: concurrent_queue - TYPE_0, concurrency=2
echo "[1/2] concurrent_queue: TYPE_0, max-concurrency=2"
run_name="concurrent_queue_TYPE_0_CONCURRENCY_2_ROUND1"
extra_args="--task-type 0 --max-concurrency 2 --submit-interval 100us --task-count 512 --task-duration 1000us --qos-class 2 --parameters $run_name"
run_single_test "concurrent_queue" "$run_name" "$extra_args"
echo ""


echo ""
echo ""
echo "=== All tests complete ==="
# Find actual trace file/directory
TRACE_DIR=$(find "$RESULT_FOLDER" -name "*.trace" -type d | head -1)
if [ -z "$TRACE_DIR" ]; then
    echo "❌ No trace directory found in $RESULT_FOLDER"
    echo "📁 Directory contents:"
    ls -la "$RESULT_FOLDER"
    exit 1
fi
echo ""
echo "Trace directory: $TRACE_DIR"
echo ""
echo "Checking trace contents..."
xcrun xctrace export --input "$TRACE_DIR" --toc 2>&1 | grep 'schema=' | grep -o 'schema="[^"]*"' | sort -u
echo ""

# Parse the trace file automatically using batch parser
echo "=== Parsing trace and generating CSV ==="
python3 "$PROJECT_DIR/batch_parse_traces.py" "$RESULT_FOLDER"

# Find the generated CSV file
CSV_FILE=$(find "$RESULT_FOLDER" -name "*.csv" -type f | head -1)
if [ -f "$CSV_FILE" ]; then
    echo "✅ Results saved to: $CSV_FILE"
    echo ""
    echo "📊 Quick preview:"
    if command -v column >/dev/null 2>&1; then
        head -10 "$CSV_FILE" | column -t -s ','
    else
        head -10 "$CSV_FILE"
    fi
else
    echo "❌ Failed to generate CSV file"
fi

echo ""
echo "Done!"
echo ""
echo "📁 Results folder: $RESULT_FOLDER"
echo "📁 Trace directory: $TRACE_DIR"
echo "📁 CSV file: $CSV_FILE"
echo ""
echo "Usage:"
echo "  ./record_all_trace_mini.sh [device] [output_dir]"
echo "  Example: ./record_all_trace_mini.sh 'iPad' ~/Desktop"
echo ""
